﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using GPSTrackingWebsiteManager.ClassManager;

namespace GPSTrackingWebsiteManager.Manager.Pages
{
    public partial class VPCControl : ClassManager.SessionManagerPage
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                DateSelectedBegin.SelectedDate = DateTime.Now;
                DateSelectedEnd.SelectedDate = DateTime.Now;
                
                GridSortExpression expression = new GridSortExpression();
                expression.FieldName = GPSTrackingDBV2.Entities.VpcControlColumn.NumCard.ToString();
                expression.SetSortOrder("Ascending");
                this.VPCControlGrid.MasterTableView.SortExpressions.AddSortExpression(expression);
            }
        }

        protected void uscDriverSearch_OnAcceptEvent(List<GridDataItem> rows)
        {
            foreach (GridDataItem row in rows)
            {
                txtDriverID.Text = row.Cells[3].Text;
                txtDriverName.Text = row.Cells[5].Text;
                txtIdentification.Text = row.Cells[4].Text;
                txtName.Text = row.Cells[6].Text;
                txtFirstSurname.Text = row.Cells[7].Text;
                txtSecondSurname.Text = row.Cells[8].Text;
                txtPhone.Text = row.Cells[9].Text;
            }
            resizeGrid();
        }

        protected void uscGPSSearch_OnAcceptEvent(List<GridDataItem> rows)
        {
            foreach (GridDataItem row in rows)
            {
                txtImei.Text = row.Cells[3].Text;
                txtImeiName.Text = row.Cells[4].Text;
                txtSimNumber.Text = row.Cells[5].Text;
                txtDescription.Text = row.Cells[6].Text;
            }
            resizeGrid();
        }

        protected void uscBusRoutesSearch_OnAcceptEvent(List<GridDataItem> rows)
        {
            foreach (GridDataItem row in rows)
            {
                txtBusRouteID.Text = row.Cells[3].Text;
                txtBusRouteName.Text = row.Cells[4].Text;
            }
            resizeGrid();
        }

        protected void uscDriverSearch_OnCancelEvent() {
            resizeGrid();
        }

        protected void uscGPSSearch_OnCancelEvent()
        {
            resizeGrid();
        }

        protected void uscBusRoutesSearch_OnCancelEvent()
        {
            resizeGrid();
        }
        
        protected void VPCControlGrid_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
        {
            try
            {
                if (DateSelectedBegin.SelectedDate != null)
                {
                    if (!isDate(DateSelectedBegin.SelectedDate.Value.ToString()))
                    {
                        showWarningMessage("La fecha selecionada no es válida.");
                        return;
                    }

                    VPCControlGrid.DataSource = GPSTrackingDBV2Custom.Data.DataRepository.VPCControlProvider.GetByDateByCompanyID(DateSelectedBegin.SelectedDate.Value, DateSelectedEnd.SelectedDate.Value, getSessionManager().CompanyIDSelectedComboBox);
                }
                else
                {
                    showInfoMessage("No se ha seleccionado la fecha de consulta.");
                }
            }
            catch (Exception ex)
            {
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);
                showErrorMessage("No se pudo obtener la información.");
            }
        }

        public bool isDate(string date)
        {
            try
            {
                DateTime.Parse(date);
                return true;
            }
            catch
            {
                return false;
            }
        }

        protected void btnSearchVPCControlGrid_Click(object sender, EventArgs e)
        {
            serchVPCControl();
        }

        protected void serchVPCControl()
        {
            try
            {
                if (DateSelectedBegin.SelectedDate != null)
                {
                    if (!isDate(DateSelectedBegin.SelectedDate.Value.ToString()))
                    {
                        showWarningMessage("La fecha selecionada no es válida.");
                        return;
                    }
                    VPCControlGrid.DataSource = GPSTrackingDBV2Custom.Data.DataRepository.VPCControlProvider.GetByDateByCompanyID(DateSelectedBegin.SelectedDate.Value, DateSelectedEnd.SelectedDate.Value, getSessionManager().CompanyIDSelectedComboBox);
                    VPCControlGrid.DataBind();
                    resizeGrid();
                }
                else
                {
                    showInfoMessage("No se ha seleccionado la fecha de consulta.");
                }
            }
            catch (Exception ex)
            {
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);
                showErrorMessage("No se pudo consultar la información.");
            }
        }
        protected void btnAddBusRoutes_Click(object sender, EventArgs e)
        {
            DateTime dateBegin;
            DateTime dateEnd;
            DateTime dateSelected;
            DateTime dateMin;
            DateTime dateMax;

            string result;

            List<DateTime> dates = new List<DateTime>();
            List<DateTime> datesBegin = new List<DateTime>();
            List<DateTime> datesEnd = new List<DateTime>();

            dates.Clear();
            datesBegin.Clear();
            datesEnd.Clear();

            if (RadCalendar1.SelectedDates.Count == 0) {
                showInfoMessage("Debe seleccionar almenos un día para el registro.");
                return;
            }

            if (string.IsNullOrEmpty(txtDriverID.Text))
            {
                showInfoMessage("Debe seleccionar el conductor.");
                return;
            }

            if (string.IsNullOrEmpty(txtImei.Text))
            {
                showInfoMessage("Debe seleccionar el vehículo.");
                return;
            }

            if (string.IsNullOrEmpty(txtBusRouteID.Text))
            {
                showInfoMessage("Debe seleccionar la Ruta.");
                return;
            }

            if (!RadTimePicker1.SelectedDate.HasValue)
            {
                showInfoMessage("Debe seleccionar la hora desde.");
                return;
            }

            if (!RadTimePicker2.SelectedDate.HasValue)
            {
                showInfoMessage("Debe seleccionar la hora hasta.");
                return;
            }

            if (RadTimePicker2.SelectedDate.Value <= RadTimePicker1.SelectedDate.Value)
            {
                showWarningMessage("La fecha Hasta no puede ser menor o igual a la fecha Desde.");
                return;
            }
            
            dateMin = DateTime.Now.Date;
            dateMax = DateTime.Now.Date;

            foreach (object date in RadCalendar1.SelectedDates)
            {
                dateSelected = ((RadDate)date).Date;

                if (dateMin.Date > dateSelected.Date)
                {
                    dateMin = dateSelected;
                }

                if (dateMax.Date < dateSelected.Date) {
                    dateMax = dateSelected;
                }
                
                dates.Add(dateSelected);
                
                dateBegin = DateTime.Parse(String.Format("{0:yyyy/MM/dd}", dateSelected) + " " + String.Format("{0:H:mm:ss tt}", RadTimePicker1.SelectedDate.Value));
                datesBegin.Add(dateBegin);

                dateEnd = DateTime.Parse(String.Format("{0:yyyy/MM/dd}", dateSelected) + " " + String.Format("{0:H:mm:ss tt}", RadTimePicker2.SelectedDate.Value));
                datesEnd.Add(dateEnd);
            }
            
            result = GPSTrackingDBV2Custom.Data.DataRepository.VPCControlProvider.Insert(getSessionManager().CompanyIDSelectedComboBox, dates, int.Parse(txtDriverID.Text), txtImei.Text, int.Parse(txtBusRouteID.Text), datesBegin, datesEnd);

            if (!string.IsNullOrEmpty(result))
            {
                showWarningMessage("No se registraron las siguientes fechas: " + result);
            }

            DateSelectedBegin.SelectedDate = dateMin;
            DateSelectedEnd.SelectedDate = dateMax;

            serchVPCControl();

            //String.Format("{0:dd/MM/yyyy}", RadCalendar1.SelectedDates[1].Date);
            //RadCalendar1.SelectedDates.Clear();
        }

        protected void VPCControlGrid_DeleteCommand(object sender, GridCommandEventArgs e)
        {
            try
            {
                GridEditableItem item = e.Item as GridEditableItem;
                Hashtable Registro = new Hashtable();
                item.ExtractValues(Registro);

                GPSTrackingDBV2Custom.Data.DataRepository.VPCControlProvider.DeleteByNumControl(int.Parse(item["NumControl"].Text));
            }
            catch (Exception ex)
            {
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);            
                showErrorMessage("No se pudo borrar el registro.");
            }
        }

        protected void lbClearFilters_Click(object sender, EventArgs e)
        {
            VPCControlGrid.MasterTableView.FilterExpression = string.Empty;

            foreach (GridColumn column in VPCControlGrid.MasterTableView.RenderColumns)
            {
                if (column is GridBoundColumn)
                {
                    GridBoundColumn boundColumn = column as GridBoundColumn;
                    boundColumn.CurrentFilterValue = string.Empty;
                }
            }
            VPCControlGrid.MasterTableView.Rebind();
        }

        protected void resizeGrid()
        {
            VPCControlGrid.Height = Unit.Parse((float.Parse(HiddenFieldHeight.Value.ToString()) - 260).ToString());
        }

        protected SessionManager getSessionManager()
        {
            return (SessionManager)HttpContext.Current.Session["SessionManager"];
        }

        protected void lbShowError_Click(object sender, EventArgs e)
        {
            showErrorMessage(HiddenFieldError.Value);
        }

        public void showErrorMessage(string msg)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "objWindowsMessageManager.show_Error", "objWindowsMessageManager.show_Error('" + msg + "','Resumen de Rutas...');", true);
        }

        public void showInfoMessage(string msg)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "objWindowsMessageManager.show_Info", "objWindowsMessageManager.show_Info('" + msg + "','Resumen de Rutas...');", true);
        }

        public void showWarningMessage(string msg)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "objWindowsMessageManager.show_Warning", "objWindowsMessageManager.show_Warning('" + msg + "','Resumen de Rutas...');", true);
        }

    }
}